//
//  InsurancePrintController.m
//  mywork
//
//  Created by li on 2018/5/11.
//  Copyright © 2018年 li. All rights reserved.
//

#import "InsurancePrintController.h"
#import "HLPrinter.h"
#import "HLBLEManager.h"
#import "NSString+Length.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "PrintPopWindow.h"
#import "UIImage+Qrcode.h"

static int TOTAL = 48;//这里是根据你的纸张宽度试验出来的一个合适的总字数

@interface InsurancePrintController ()
{
    BOOL isConnection;
}
@property (nonatomic, strong) HLPrinter *printer;
@property (nonatomic, strong) NSMutableArray *deviceArray;  /** 蓝牙设备个数 */

@property (nonatomic, strong) CBCharacteristic *chatacter;  /**< 可写入数据的特性 */
@property (nonatomic, strong) CBPeripheral *perpheral;
@property (nonatomic, strong) NSMutableArray *infos;  /**< 详情数组 */

@property (nonatomic, strong) PrintPopWindow *popWindow;
@property (nonatomic, strong) UITextField *pageTextField;

@property (nonatomic, strong) UILabel *tipsLabel;

@end

@implementation InsurancePrintController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"打印";
    [self addTipsLabel];
    
    _printer = [[HLPrinter alloc] init];
    _deviceArray = [[NSMutableArray alloc] init];
    [self searchPrinter];
    
    UIImage *image = [UIImage imageNamed:@"left.png"];
    image = [UIImage imageNamed:@"backArrow"];
    
    UIBarButtonItem *backItm = [[UIBarButtonItem alloc] initWithImage:image style:(UIBarButtonItemStylePlain) target:self action:@selector(pop)];
    self.navigationItem.leftBarButtonItem = backItm;
}

- (void)addTipsLabel{
    _tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, kScreenW - 20 * 2, 60)];
    _tipsLabel.centerY = self.view.centerY - 80;
    _tipsLabel.text = @"请打开手机蓝牙，并打开蓝牙打印机开关";
    _tipsLabel.font = [UIFont systemFontOfSize:15];
    _tipsLabel.textColor = [UIColor redColor];
    _tipsLabel.numberOfLines = 0;
    _tipsLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_tipsLabel];
}

- (void)addPrintOverView{
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.width-100)/2, self.view.height/4, 100, 100)];
    imageView.image = [UIImage imageNamed:@"printlodaing_03.png"];
    
    UILabel *dayinLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, imageView.maxY+10, self.view.width, 20)];
    dayinLabel.text = @"打印中";
    dayinLabel.textAlignment = NSTextAlignmentCenter;
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(20, dayinLabel.maxY + 80, self.view.width-40, 44)];
    [button setTitle:@"完成打印" forState:UIControlStateNormal];
    button.backgroundColor = kMainColor;
    button.layer.cornerRadius = 6;
    [button addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];

    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, button.maxY+10, button.width, 60)];
    label.text = @"打印时请勿点击按钮或退出页面，否则将会中断打印！打印完成后，点击“完成打印”继续操作！";
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor redColor];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:imageView];
    [self.view addSubview:dayinLabel];
    [self.view addSubview:button];
    [self.view addSubview:label];
}

- (void)pop{
    [self bleakBlueTooth];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 打印

-(void)searchPrinter{
    //获取打印机列表数据
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    manager.stateUpdateBlock = ^(CBCentralManager *central) {
        switch (central.state) {
            case CBCentralManagerStatePoweredOn:
                kAutoHideLoadingView(self.view, @"蓝牙已打开，并且可用",1)
//                SHOW_HUD_AUTOHIDE(@"蓝牙已打开，并且可用");
                [central scanForPeripheralsWithServices:nil options:nil];
                [self addPrinter];
                break;
            case CBCentralManagerStatePoweredOff:
                kAutoHideLoadingView(self.view, @"蓝牙可用，未打开",1)
//                SHOW_HUD_AUTOHIDE(@"蓝牙可用，未打开");
                break;
            case CBCentralManagerStateUnsupported:
                kAutoHideLoadingView(self.view, @"SDK不支持",1)
//                SHOW_HUD_AUTOHIDE(@"SDK不支持");
                break;
            case CBCentralManagerStateUnauthorized:
//                SHOW_HUD_AUTOHIDE(@"程序未授权");
                kAutoHideLoadingView(self.view, @"程序未授权",1)
                break;
            default:
                break;
        }
    };
    if (manager.centralManager.state == CBCentralManagerStatePoweredOn) {
        [manager scanForPeripheralsWithServiceUUIDs:nil options:nil];
        [self addPrinter];
    }
}

///连接打印机
- (void)connectPrint{
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    kWeakSelf
    [manager connectPeripheral:_perpheral connectOptions:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey:@(YES)}
        stopScanAfterConnected:YES servicesOptions:nil characteristicsOptions:nil completeBlock:^(HLOptionStage stage, CBPeripheral *peripheral, CBService *service, CBCharacteristic *character, NSError *error) {
            switch (stage) {
                case HLOptionStageConnection:
                {
                    if (error) {
                        kAutoHideLoadingView(self.view,@"连接失败",1);
                    } else {
                         kAutoHideLoadingView(self.view,@"连接成功",1);
//                        SHOW_HUD_AUTOHIDE(@"连接成功");
                        isConnection = YES;
                    }
                    break;
                }case HLOptionStageSeekServices:
                {
                    if (error) {
                        NSLog(@"查找服务失败");
                    } else {
                        NSLog(@"查找服务成功");
                        weakSelf.infos = [NSMutableArray array];
                        [weakSelf.infos addObjectsFromArray:peripheral.services];
                    }
                    break;
                }
                case HLOptionStageSeekCharacteristics:
                {
                    // 该block会返回多次，每一个服务返回一次
                    if (error) {
                        NSLog(@"查找特性失败");
                    } else {
                        NSLog(@"查找特性成功");
                    }
                    break;
                }
                case HLOptionStageSeekdescriptors:
                {
                    // 该block会返回多次，每一个特性返回一次
                    if (error) {
                        NSLog(@"查找特性的描述失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }];
}

///断开打印机
-(void)bleakBlueTooth{
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    [manager cancelPeripheralConnection];
}

- (void)addPrinter{
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    kWeakSelf
    manager.discoverPeripheralBlcok = ^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        if (peripheral.name.length <= 0) {
            return ;
        }
        if (self.deviceArray.count == 0) {
            NSDictionary *dict = @{@"peripheral":peripheral, @"RSSI":RSSI};
            [self.deviceArray addObject:dict];
        } else {
            BOOL isExist = NO;
            for (int i = 0; i < self.deviceArray.count; i++) {
                NSDictionary *dict = [self.deviceArray objectAtIndex:i];
                CBPeripheral *per = dict[@"peripheral"];
                if ([per.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
                    isExist = YES;
                    NSDictionary *dict = @{@"peripheral":peripheral, @"RSSI":RSSI};
                    [weakSelf.deviceArray replaceObjectAtIndex:i withObject:dict];
                }
            }
            
            if (!isExist) {
                NSDictionary *dict = @{@"peripheral":peripheral, @"RSSI":RSSI};
                [self.deviceArray addObject:dict];
            }
        }
        NSLog(@"蓝牙个数：%ld",(long)self.deviceArray.count);
        
        [self.tipsLabel removeFromSuperview];
        [self addPrintSubView];
        
        [self setPopWindowData];
    };
}

- (void)addPrintSubView{
    if ([_popWindow isDescendantOfView:self.view]) {
        return;
    }
    _popWindow = [[NSBundle mainBundle] loadNibNamed:@"PrintPopWindow" owner:nil options:nil].firstObject;
    _popWindow.frame = self.view.bounds;
    _popWindow.xButton.hidden = YES;
    
    kWeakSelf
    
    _popWindow.clickCell = ^(UITableViewCell *cell, NSInteger row){
        if (row <= 0 || weakSelf.deviceArray.count <= 0) {
            return ;
        }
        
        NSDictionary *dic = weakSelf.deviceArray[row-1];
        weakSelf.perpheral = dic[@"peripheral"];
        [weakSelf connectPrint];
    };
    
    _popWindow.closeBlock = ^{
//        [weakSelf.view removeFromSuperview];
        [weakSelf bleakBlueTooth];
        [weakSelf removeFromParentViewController];
    };
    
    _pageTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, _popWindow.table.width - 10 - 180, 30)];
    _pageTextField.text = @"2";
    _pageTextField.keyboardType = UIKeyboardTypePhonePad;
    _pageTextField.layer.borderWidth = 1;
    // kAutoHideLoadingView(self.view,@"连接成功",1);
    _pageTextField.layer.borderColor = kHexColor(0xe1e1e1).CGColor;
    _pageTextField.inputAccessoryView = [HSTool getInputAccessoryViewForCloseKeyboard];
    
    
    [_popWindow.daYinButton addTarget:self action:@selector(print) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_popWindow];
}

- (void)setPopWindowData{
    
    UITableViewCell *pageCell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:nil];
//    pageCell.textLabel.text = @"打印份数：";
//    pageCell.accessoryView = _pageTextField;
    pageCell.textLabel.text = @"请选择打印机进行打印";
    pageCell.textLabel.textColor = [UIColor redColor];
    pageCell.textLabel.textAlignment = NSTextAlignmentRight;
    NSMutableArray *arr = [NSMutableArray arrayWithObject:pageCell];
    for (int i = 0;i < _deviceArray.count;i++) {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
        NSDictionary *dict = [self.deviceArray objectAtIndex:i];
        CBPeripheral *peripherral = dict[@"peripheral"];
        cell.textLabel.text = [NSString stringWithFormat:@"名称:%@",peripherral.name];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        [arr addObject:cell];
    }
    _popWindow.cells = arr;
}

- (void)print{
    if (!isConnection) {
         kAutoHideLoadingView(self.view,@"打印机尚未连接成功",1);
        return;
    }
    [self addPrintOverView];
    [_popWindow removeFromSuperview];
    
    NSLog(@"开始打印");
    
    int page = [self.pageTextField.text intValue];

    [self printContent];
}

- (void)printContent{
     [self getCharacter];
    [self printHeader];
    [self printInfo];
    [self printQuote];
    [self printQRCode];
    [self printFooter];
    [self addEmpty];
    [self isWriteSucess];
}

//获取特征值
- (void)getCharacter {
    for (CBService * service in _infos) {
        for (CBCharacteristic * character in service.characteristics) {
            CBCharacteristicProperties properties = character.properties;
            if (properties & CBCharacteristicPropertyWrite) {
                self.chatacter = character;
                return;
            }
        }
    }
}

//写入是否成功
-(void)isWriteSucess{
    NSData *mainData = [_printer getFinalData];
    HLBLEManager *bleManager = [HLBLEManager sharedInstance];
//    [bleManager writeValue:mainData forCharacteristic:self.chatacter type:CBCharacteristicWriteWithoutResponse];
    
    if (self.chatacter.properties & CBCharacteristicPropertyWrite) {
        [bleManager writeValue:mainData forCharacteristic:self.chatacter type:CBCharacteristicWriteWithResponse completionBlock:^(CBCharacteristic *characteristic, NSError *error) {
            NSLog(@"错误：%@",error);
            if (!error) {
                NSLog(@"写入成功");
            }
        }];
    }
//    else if (self.chatacter.properties & CBCharacteristicPropertyWriteWithoutResponse) {
//        [bleManager writeValue:mainData forCharacteristic:self.chatacter type:CBCharacteristicWriteWithoutResponse];
//    }
}


- (void)printHeader{
    
    UIImage *image = [UIImage imageNamed:@"dayin-quote.jpg"];
    NSString *companyName = _printData.companyInfo.name ?:@"";
    
    
    NSString *line = [self addOnceText:@"_"];
    NSString *address = [NSString stringWithFormat:@"地址:%@",_printData.companyInfo.address?:@""];
    NSString *mob = [NSString stringWithFormat:@"电话:%@",_printData.companyInfo.complainTel ?:@""];
    NSString *time = [NSString stringWithFormat:@"报价时间:%@",_printData.quoteOrder.quoteDate ?:@""];
    
    [self.printer appendImage:image alignment:HLTextAlignmentCenter maxWidth:560];
    [self.printer appendText:companyName alignment:HLTextAlignmentCenter];
    
    [self.printer appendText:address alignment:HLTextAlignmentLeft];
    [self.printer appendText:mob alignment:HLTextAlignmentLeft];
    [self.printer appendText:line alignment:HLTextAlignmentCenter];
    [self.printer appendSpace];
    [self.printer appendText:time alignment:(HLTextAlignmentLeft)];
    [self.printer appendText:line alignment:HLTextAlignmentCenter];
}

- (void)printInfo{
    NSString *vin = [NSString stringWithFormat:@"%@",_printData.quoteOrder.carVin ?:@""];
    NSString *lastForceExpireDate = [NSString stringWithFormat:@"%@",_printData.lastForceExpireDate ?:@""];
    NSString *carModel = [NSString stringWithFormat:@"%@",_printData.quoteOrder.modelName ?:@""];
    
    NSString *engineNo = [NSString stringWithFormat:@"%@",_printData.quoteOrder.engineNo ?:@""];
    NSString *lastBizExpireDate = [NSString stringWithFormat:@"%@",_printData.lastBizExpireDate ?:@""];
    NSString *line = [self addOnceText:@"_"];
    
    [_printer appendTitle:@"车牌:" value:_printData.licenseNo ?:@""];
    [_printer appendTitle:@"车主:" value:_printData.quoteOrder.name ?:@""];
    [_printer appendTitle:@"被保险人:" value:_printData.holderName ?:@""];
//    [_printer appendTitle:clientName value:carNo];
//    [_printer appendTitle:insuredName value:name];
    
    [_printer appendTitle:@"车型:" value:carModel];
    [_printer appendTitle:@"发动机号:" value:engineNo];
    [_printer appendTitle:@"车架号:" value:vin];
    
    [_printer appendTitle:@"交强险到期时间:" value:lastForceExpireDate];
    [_printer appendTitle:@"商业险到期时间:" value:lastBizExpireDate];
    
    [_printer appendText:line alignment:HLTextAlignmentCenter];
}

- (void)printQuote{
    NSString *company = [NSString stringWithFormat:@"投保公司  %@\n",_printData.insurerName ?:@""];
    [_printer appendText:company alignment:(HLTextAlignmentCenter)];
    
//    [_printer addLittleTitle:@"承保险种" value:@"保险金额/应交保费"];
    [_printer appendTitle:@"承保险种/保险金额" value:@"应交保费"];
    NSString *line = [self addOnceText:@"_"];
    
    for (InsurerQuoteItem *item in _printData.insurerQuoteItems) {
        if (item.amount.intValue == 0) {
            continue;
        }
        
        NSString *amount = item.amount ?:@"";
        if (item.amount.floatValue > 10000) {
            amount = [NSString stringWithFormat:@"%.1f万",item.amount.floatValue / 10000.0];
        }
        
        if ([item.field isEqualToString:@"BoLi"] || [item.field isEqualToString:@"HcXiuLiChang"]) {
            amount = item.amount.intValue == 1 ? @"国产" : @"进口";
        }else if (item.amount.intValue == 1){
            amount = @"投保";
        }
        
        NSString *name = [NSString stringWithFormat:@"%@(%@)",item.name?:@"", amount];
        NSString *value = item.amountPrice?:@"";
        [_printer appendTitle:name value:value];
    }
    
    [_printer appendText:@"\n" alignment:(HLTextAlignmentCenter)];
    [_printer appendTitle:@"商业险合计" value: [NSString stringWithFormat:@"￥%@",_printData.bizTotal ?:@""]];
    [_printer appendTitle:@"交强险" value:[NSString stringWithFormat:@"￥%@",_printData.forceTotal ?:@""]];
    [_printer appendTitle:@"车船税" value:[NSString stringWithFormat:@"￥%@",_printData.taxTotal ?:@""]];
    if (_printData.cutPrice.intValue > 0) {
        [_printer appendTitle:@"优惠金额" value:[NSString stringWithFormat:@"￥%@",_printData.cutPrice ?:@""]];
    }
    [_printer appendTitle:@"优惠后金额" value:[NSString stringWithFormat:@"￥%@",_printData.totalPrice ?:@""]];
    [_printer appendText:line alignment:HLTextAlignmentCenter];
}

- (void)printHistory{
    [_printer appendText:@"上年出险记录" alignment:(HLTextAlignmentCenter)];
    NSString *biz = [NSString stringWithFormat:@"商业险：出险%d次",2];
    NSString *force = [NSString stringWithFormat:@"交强险：出险%d次",2];
    
    [_printer appendText:biz alignment:(HLTextAlignmentLeft)];
    [_printer appendText:force alignment:(HLTextAlignmentRight)];
    [_printer appendSeperatorLine];
}

- (void)printQRCode{
    NSString *line = [self addOnceText:@"_"];
    NSString *qrCode = _printData.shareUrl ?:@"";
//    [_printer appendQRCodeWithInfo:qrCode];
//    [_printer appendQRCodeWithInfo:qrCode size:60];
    UIImage *image = [UIImage getQrcodeImageWithString:qrCode size:CGSizeMake(200, 200)];
    [_printer appendImage:image alignment:HLTextAlignmentCenter maxWidth:200];
    [_printer appendText:@"扫码获取电子保单" alignment:(HLTextAlignmentCenter)];
    [_printer appendText:line alignment:HLTextAlignmentCenter];

}

- (void)printFooter{
    NSString *string = @"尊敬的客户:此报价单仅作为保费的初步估算,仅供参考,最终投保险种及保费以保险单为准;请您详细核对,并将您的要求通知我们,我们会尽快与您联系,谢谢!";
    NSString *line = [self addOnceText:@"- "];
    [_printer appendText:string alignment:(HLTextAlignmentLeft)];
    [_printer appendText:line alignment:HLTextAlignmentCenter];
    [_printer appendTitle:@"业务员签字：" value:@"客户签字：" valueOffset:280];
    [_printer appendText:@"\n" alignment:(HLTextAlignmentCenter)];
    [_printer appendTitle:@"业务员电话：" value:@"客户电话：" valueOffset:280];
    [_printer appendSpace];
    [_printer appendSpace];
}


- (void)addEmpty{
    NSString *string = @"\n\n";
    [_printer appendText:string alignment:HLTextAlignmentCenter];
}

- (NSString *)addOnceText:(NSString *)text{
    int onceLength = text.chartLength;
    NSMutableString *string = [NSMutableString string];
    for (int i = 0; i < TOTAL/onceLength; i++) {
        [string appendString:text];
    }
    return string;
}

@end
